import { getRdsSysConfig } from './init';

/**
     * @description 四舍五入（非银行家算法）
 */
const round = (d, digits) => {
    return Math.round(d * Math.pow(10, digits)) / Math.pow(10, digits);
}

const calcAtInByPt = (prop = { c_pt, c_n }) => {
    const { c_pt = 0, c_n = 0 } = prop;
    const a = round((c_pt * c_n || 0), 2)
    return a;
}
/**
 * @description 不含税金额保留小数位数 默认值2
*/

/**
 * @description 根据不含税价计算不含税金额
*/
const calcAetInByPet = async(props: { c_pet: number, c_n: number }) => {
	const { c_pet, c_n } = props
	const aetDigits: number = Number(await getRdsSysConfig('进销存管理参数',"不含税金额保留小数位数") || '2');
	return round((c_pet * c_n || 0), aetDigits)
}

/**
 * @description 根据结算价计算进价
*/
const calcPtInByPtPay = (prop = { c_pt_pay, c_tax_rate_pay, c_tax_rate, c_tax_src }) => {
    const { c_pt_pay = 0, c_tax_rate_pay = 0, c_tax_rate = 0, c_tax_src = '' } = prop;
    //结算价/(1+进项税率)=进价/(1+销项税率)
    // 免税：结算价*(1-进项税率)=进价/(1+销项税率)
    if (c_tax_src === 'F') {
        return round(c_pt_pay * (1 + c_tax_rate / 100) * (1 - c_tax_rate_pay / 100), 4);
    } else {
        if (c_tax_rate_pay !== c_tax_rate && isTaxRateDiffCalPrice === '1') {

            return round(c_pt_pay * (1 + c_tax_rate / 100) / (1 + c_tax_rate_pay / 100), 4);
        } else {

            return +c_pt_pay;
        }
    }
}

/**
 * @description 根据含税结算价计算不含税结算价
*/
const calcPetpayByPtPay = (props = { c_pt_pay, c_tax_rate_pay, c_tax_src }) => {
    const { c_pt_pay = 0, c_tax_rate_pay = 0, c_tax_src = '' } = props;
    if (c_tax_rate_pay === 0) {
        return +c_pt_pay;
    }
    if (c_tax_src === 'F') {
        return round(c_pt_pay * (1 - c_tax_rate_pay / 100), 4);
    } else {
        return getPetFormMula(c_pt_pay, c_tax_rate_pay);
    }
}

/**
 * @description 根据含税计算不含税公式
 * */
const getPetFormMula = (amountPt, rate) => {
    return round(amountPt / (1 + rate / 100), 4);
}

/**
 *
 * @param n 录入数量
 * @param p 包装含量
 * @returns
 */
const calculatePackages = async (p, n) => {
    const npack = Math.floor(n / p); // 计算整包数
    const odd = n % p; // 计算零数

    // 转化为小数并保留两位小数
    const npackDecimal = parseFloat(npack.toFixed(2));
    const oddDecimal = parseFloat(odd.toFixed(2));
    return {
        npack: npackDecimal,
        odd: oddDecimal
    };
}
/**
 * 获取数字的全部约数
 * @param d 指定数字
 * @returns 约数数组
 */
const getDivisors = (d) => {
    const divisors = [];
    for (let i = 2; i < Math.sqrt(d) + 1; i++) {
        const a = d % i;
        if (a === 0) {
            divisors.push(i);
            if (d / i > 1) {
                divisors.push(d / i);
            }
        }
    }
    return divisors;
}

/**
 *
 * @param inputOdd 录入零数
 * @param npack 当前件数
 * @param pack 包装含量
 * @param unpack 是否拆零
 * @returns
 */
const validateOddLot = (inputOdd, npack, pack, unpack) => {
    inputOdd = Number(inputOdd)
    let validateResult = {};
    const odd = inputOdd % pack;
    if (pack !== 1) {
        if (unpack === '0') {
            if (odd !== 0) {
                validateResult.result = {
                    message: '不可拆零，必须录入含量的整数倍',
                    validated: false,
                };
                return validateResult;
            }
        } else if (unpack === '2') {
            const divisors = getDivisors(pack);
            if (divisors.length > 0) {
                if (!divisors.some(i => inputOdd % i === 0)) {
                    validateResult.result = {
                        message: '仅约数可拆零，录入数量不是含量的约数',
                        validated: false,
                    };
                    return validateResult;
                }
            } else {
                if (inputOdd % pack !== 0) {
                    validateResult.result = {
                        message: '仅约数可拆零，录入数量不是含量的约数',
                        validated: false,
                    };
                    return validateResult;
                }
            }
        }
    }
    if (inputOdd >= pack) {
        validateResult.npack = Math.floor(inputOdd / pack);
        validateResult.n = inputOdd;
        validateResult.result = {
            message: '',
            validated: true,
            retValue: odd,
        };
    } else {
        validateResult.npack = npack;
        validateResult.n = validateResult.npack * pack + inputOdd;
        validateResult.result = {
            message: '',
            validated: true,
            retValue: inputOdd,
        };
    }
    return validateResult;
};

/**
 * @description 验证毛利率
 */
const validateProfitLimit = (props) => {
    let { currentProfit = 0, profitLimitlow = -30, profitLimitTop = 50, gdsPriceSence = 'Y' } = props;

    let topLimitMethod = getRdsSysConfig("采购管理参数", "品类毛利率上限控制方法");
    let lowLimitMethod = getRdsSysConfig("采购管理参数", '品类毛利率下限控制方法');

    switch (gdsPriceSence) {
        case 'V': // 超敏感
            return {
                validated: true
            };
        case 'Y': // 敏感
            if (currentProfit < 0) {
                return {
                    message: `价格敏感度为敏感的商品毛利率不可小于0！`,
                    validated: false
                }
            }
            break;
        case 'N':// 不敏感
            if (currentProfit > profitLimitTop) {
                switch (topLimitMethod) {
                    case '1':
                        return {
                            message: `毛利率${currentProfit}%超出毛利率上限${profitLimitTop}%！`,
                            validated: false
                        }
                    case '2':
                        return {
                            message: `毛利率${currentProfit}%超出毛利率上限${profitLimitTop}%！`,
                            validated: true
                        }
                }
            }
            if (currentProfit < profitLimitlow) {
                switch (lowLimitMethod) {
                    case '1':
                        return {
                            message: `毛利率${currentProfit}%低于毛利率下限${profitLimitlow}%！`,
                            validated: false
                        }
                    case '2':
                        return {
                            message: `毛利率${currentProfit}%低于毛利率下限${profitLimitlow}%！`,
                            validated: true
                        }
                }
            }
            break;
    }
    return {
        validated: true
    };
}

// 进行取8、取9数值计算
function calcPrecision(props) {
    const { inputPrice, pre, modeValue } = props;
    let direction = getRdsSysConfig("系统参数","价格精度尾数处理方向");
    let rema = inputPrice * Math.pow(10, pre) % 10;
    let result = 0;
    if (direction === 'up') {
        if (rema >= modeValue) {
            result = (Math.floor(inputPrice * Math.pow(10, pre - 1)) + (modeValue * 0.1)) * 10 / Math.pow(10, pre);
        } else {
            result = (Math.ceil(inputPrice * Math.pow(10, pre - 1)) + (modeValue * 0.1)) * 10 / Math.pow(10, pre);
        }
    } else if (direction === 'down') {
        if (rema >= modeValue) {
            result = (Math.ceil(inputPrice * Math.pow(10, pre - 1)) - (1 - modeValue * 0.1)) * 10 / Math.pow(10, pre);
        } else {
            result = (Math.floor(inputPrice * Math.pow(10, pre - 1)) - (1 - modeValue * 0.1)) * 10 / Math.pow(10, pre);
        }
    } else {
        const cent = (modeValue + 5) % 10;
        if (modeValue > cent) {
            if (cent <= rema && rema <= modeValue) {
                result = (Math.ceil(inputPrice * Math.pow(10, pre - 1)) - (1 - modeValue * 0.1)) * 10 / Math.pow(10, pre);
            } else {
                if (rema > modeValue) {
                    result = (Math.ceil(inputPrice * Math.pow(10, pre - 1)) - (1 - modeValue * 0.1)) * 10 / Math.pow(10, pre);
                } else {
                    result = (Math.floor(inputPrice * Math.pow(10, pre - 1)) - (1 - modeValue * 0.1)) * 10 / Math.pow(10, pre);
                }
            }
        } else {
            if (modeValue <= rema && rema < cent) {
                result = (Math.ceil(inputPrice * Math.pow(10, pre - 1)) - (1 - modeValue * 0.1)) * 10 / Math.pow(10, pre);
            } else {
                if (rema < modeValue) {
                    result = (Math.floor(inputPrice * Math.pow(10, pre - 1)) + (modeValue * 0.1)) * 10 / Math.pow(10, pre);
                } else {
                    result = (Math.ceil(inputPrice * Math.pow(10, pre - 1)) + (modeValue * 0.1)) * 10 / Math.pow(10, pre);
                }
            }
        }
    }
    return result < 0 ? 0 : result;
}

// 对小数位进行计算
function calcPriceByPrecision(props) {
    const { inputPrice, priceMethod, pricePrecision } = props;

    let pre = 2;

    switch (pricePrecision) {
        case 'f':
            pre = 2;
            break;
        case 'j':
            pre = 1;
            break;
        case 'y':
            pre = 0;
            break;
        case 's':
            pre = -1;
            break;
    }

    switch (priceMethod) {
        case '0':
            return round(inputPrice, pre);
        case '1':
            return Math.floor(inputPrice * Math.pow(10, pre)) / Math.pow(10, pre);
        case '2':
            return Math.ceil(inputPrice * Math.pow(10, pre)) / Math.pow(10, pre);
        case '8':
            return calcPrecision({ inputPrice, pre, modeValue: 8 });
        case '9':
            return calcPrecision({ inputPrice, pre, modeValue: 9 });
    }

    return round(inputPrice, pre);
}

export {
    round,
    calcAtInByPt,
    calcPtInByPtPay,
    calcPetpayByPtPay,
    calculatePackages,
    validateOddLot,
    validateProfitLimit,
    calcPriceByPrecision,
	calcAetInByPet
}
